package com.demo.config.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.demo.common.EnumFuctionStatus;
import com.demo.model.SysMenu;
import com.demo.model.SysRole;
import com.demo.model.SysUser;
import com.demo.service.UserService;
import com.demo.service.MenuService;
import com.demo.service.RoleService;

public class MyRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private MenuService menuService;

	/**
	 * 认证回调函数,登录时调用.
	 *
	 * @param authcToken
	 *            登录信息集合
	 * @return AuthenticationInfo
	 * @throws AuthenticationException
	 *             认证异常
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		SysUser sysUser = userService.getByUsernames(token.getUsername());
		// 账号不存在
		if (sysUser == null)
			throw new UnknownAccountException();// 没找到帐号
		if (EnumFuctionStatus.BAD_STATUS.getCode().equals(sysUser.getDelFlag()))
			throw new LockedAccountException();
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(sysUser.getUsername(),
				sysUser.getPassword(), ByteSource.Util.bytes(sysUser.getSalt()), getName());
		Session session = SecurityUtils.getSubject().getSession();
		session.setAttribute("user", sysUser);
		return simpleAuthenticationInfo;
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 *
	 * @param principals
	 *            授权信息
	 * @return AuthorizationInfo
	 */
	public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String loginName = (String) principals.fromRealm(getName()).iterator().next();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		SysRole sysRole = roleService.findUserRole(loginName);
		if (null == sysRole) {
			return info;
		}
		info.addRole(sysRole.getRoleName());
		List<SysMenu> menuList = menuService.findAll(sysRole.getRoleId());
		List<String> lists = new ArrayList<String>();
		for (SysMenu menu : menuList) {
			lists.add(menu.getPermission());
		}
		info.addStringPermissions(lists);
		return info;
	}

	/**
	 * 更新用户授权信息缓存.
	 *
	 * @param principal
	 *            用户标志
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}
}